import bundleManager from '@ohos.bundle.bundleManager';
import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';

async function checkAccessToken(permission: Permissions): Promise<abilityAccessCtrl.GrantStatus> {
  let atManager = abilityAccessCtrl.createAtManager();
  let grantStatus: abilityAccessCtrl.GrantStatus;

  // 获取应用程序的accessTokenID
  let tokenId: number;
  try {
    let bundleInfo: bundleManager.BundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
    console.log('Detector.checkAccessToken===========bundleInfo=', JSON.stringify(bundleInfo));
    let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo;
    console.log('Detector.checkAccessToken===========appInfo=', JSON.stringify(appInfo));
    tokenId = appInfo.accessTokenId;
    console.log('Detector.checkAccessToken===========tokenId=', tokenId);
  } catch (err) {
    console.error(`getBundleInfoForSelf failed, code is ${err.code}, message is ${err.message}`);
  }

  // 校验应用是否被授予权限
  try {
    grantStatus = await atManager.checkAccessToken(tokenId, permission);
    console.log('Detector.checkAccessToken===========grantStatus=', tokenId);
  } catch (err) {
    console.error(`checkAccessToken failed, code is ${err.code}, message is ${err.message}`);
  }

  return grantStatus;
}

/**
 * ohos.permission.READ_CALENDAR
 * ohos.permission.LOCATION
 * Permissions包含所有的设备权限
 * @returns
 */
async function checkAccess(): Promise<Boolean> {
  const permissions: Array<Permissions> = ['ohos.permission.LOCATION'];
  console.log('checkAccess====01=');
  let grantStatus: abilityAccessCtrl.GrantStatus = await checkAccessToken(permissions[0]);
  console.log('checkAccess====02=', JSON.stringify(grantStatus));
  if (grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
    // 已经授权
    return true;
  } else {
    // 未授权
    return false;
  }
}

export { checkAccess }